using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MVC.Models;
using MVC.Models.Database;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace MVC.Controllers
{
    // 特性路由
    // [Route("/")]
    // [Route("[controller]/[action]")]
    public class LoginController : Controller
    {
        // 数据库连接注入
        private readonly LifengContext _context;
        public LoginController(LifengContext context)
        {
            _context = context;
        }
        // [Route("/")]
        [Route("/[controller]")]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 用于登录的请求
        /// </summary>
        [HttpPost]
        [Route("/api/users/login")]
        public IActionResult LoginAccount(LoginAccountRequest request)
        {
            // return Json(request);
            // 如果用户名和密码正确返回登录成功
            if (_context.Users.Where(u => u.UserName == request.username && u.UserPassword == request.password).Count() > 0)
            {
                // 登录成功后设置cookie
                var claims = new List<Claim>
                {
                new Claim(ClaimTypes.Name, request.username),
                new Claim(ClaimTypes.Thumbprint, request.password),
                };
                HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)));
                return Json(new { status = "success", data = request.username, msg = "登录成功" });
            }
            return Json(new { status = "fail", data = "登录失败" });
            //存在的话 走登录流程
        }
    }
}